package com.question.task;

import com.question.mapper.UserMapper;
import com.question.pojo.vo.AdviceVO;
import com.question.service.IQuestionService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 预热用户建议定时任务
 */
@Component
@Slf4j
public class AdviceWarmUpTask {

    @Autowired
    private IQuestionService questionService;
    @Autowired
    private UserMapper userMapper;

    private static final int BATCH_SIZE = 10; // 每次轮询处理的用户数量
    private int lastUserId = 0; // 记录上次轮询的最后用户ID

    @Bean
    public TaskScheduler adviceWarmUpScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(1); // 专用线程数
        scheduler.setThreadNamePrefix("advice-warmup-");
        return scheduler;
    }

    // 每小时预热一次
    @Scheduled(cron = "0 5 * * * ?",scheduler = "adviceWarmUpScheduler" )
    public void warmUpAdvice(){
        log.info("开始每小时用户学习建议数据预热...");
        List<Long> userIds = userMapper.selectUsersForWarmUp(lastUserId,BATCH_SIZE);

        for (Long userId : userIds) {
            AdviceVO advice = questionService.getAdvice(userId,false);

            log.info("用户id:{} 学习建议预热成功:{}",userId,advice);
        }

        lastUserId = userIds.get(userIds.size() - 1).intValue();
        log.info("本轮预热完成，处理了 {} 个用户，最后用户ID: {}", userIds.size(), lastUserId);
    }

    /**
     * 项目启动时进行一次预热
     */
    @Async
    @PostConstruct
    public void initWarmUpAdvice() {
        log.info("项目启动时进行用户学习建议数据预热...");
        List<Long> userIds = userMapper.selectUsersForWarmUp(lastUserId, BATCH_SIZE);
        for (Long userId : userIds) {
            AdviceVO advice = questionService.getAdvice(userId, false);

            log.info("用户id:{} 学习建议预热成功", userId);
        }
        if (!userIds.isEmpty()) {
            lastUserId = userIds.get(userIds.size() - 1).intValue();
        }
        log.info("启动时预热完成，处理了 {} 个用户，最后用户ID: {}", userIds.size(), lastUserId);
    }


}
